<template>
  <div ref="donutChart" :style="{ width: width, height: height }"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'DonutChart',
  props: {
    seriesName: {
      type: String,
      default: () => {
        return ''
      }
    },
    height: {
      type: String,
      default: () => {
        return '100%'
      }
    },
    width: {
      type: String,
      default: () => {
        return '100%'
      }
    },
    // 接收数据数组
    dataList: {
      type: Array,
      required: false,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      electricityData: [
        // { value: 1048, name: 'Search Engine' },
        // { value: 735, name: 'Direct' },
        // { value: 580, name: 'Email' },
        // { value: 484, name: 'Union Ads' },
        // { value: 300, name: 'Video Ads' }
      ]
    }
  },
  watch: {
    dataList: {
      handler(v) {
        this.electricityData = v;
        this.initChart();
      },
      deep: true
    }
  },
  mounted() {
    this.initChart();
  },
  methods: {
    listener(chartDom, myChart) {
      const resizeObserver = new ResizeObserver(() => {
        if (myChart) {
          myChart.resize();
        }
      });
      resizeObserver.observe(chartDom);
    },
    initChart() {
      const chartDom = this.$refs.donutChart;
      const myChart = echarts.init(chartDom);
      const option = {
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: this.seriesName,
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            data: this.electricityData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart.setOption(option);
      this.listener(chartDom, myChart)
    },
  },
};
</script>

<style scoped>
/* 你可以在这里添加组件的样式 */
</style>